import json
import os
import time
import traceback
import configparser
import requests
import urllib3

import api
from DBAction import DBAction

urllib3.disable_warnings()
db = DBAction('pocket48')


def get_live_source():
    result = db.data_inquiry_all("SELECT m.cover,r.name FROM live m left join member r on m.memberid=r.memberid "
                                 "where m.start_time>'2021-04-06 22:10:00' and m.start_time<'2021-06-09 08:00:00'")
    print(len(result))

    list2 = []
    index = 0
    for i in result:
        if index < 400:
            index += 1
            continue
        if i not in list2:
            list2.append(i)
    print(len(list2))

    for data in list2:
        if 'https' in data[0]:
            url = data[0]
        else:
            url = f'https://source.48.cn{data[0]}'
        name = data[1]
        date_str = ''
        image_filename = data[0].split('/')[2]

        # 创建的目录
        path = f"D:/pocket48image/{name}"
        img_name = f'{path}/{image_filename}'
        if not os.path.exists(path):
            os.makedirs(path)
        try:
            html = requests.get(url, verify=False)
            with open(img_name, 'wb') as f:
                f.write(html.content)
            f.close()
        except Exception as e:
            api.logger.info(traceback.format_exc())
            print(url, e.__str__())
            print(traceback.format_exc())
            api.wait_random_time(20)
        api.wait_random_time(3)


def get_roommsg_source(cur_time, early_time):
    '''
    1 图 jpg
    3 语音 aac
    4 视频 mov
    '''
    result = db.data_inquiry_all("SELECT m.name,r.msg_type,r.ext_info,r.msg_time "
                                 "FROM pocket48.roommsg r left join "
                                 "member m on m.memberid=r.memberid where r.msg_type in (1,4,3) "
                                 f"and r.msg_time>'{early_time}' and r.msg_time<'{cur_time}'")
    print(len(result))
    total = len(result)
    count = 0.0
    for data in result:
        url = data[2]
        name = data[0]
        filename = data[3].strftime("%Y-%m-%d_%H-%M-%S")
        type = data[1]
        if type == 1:
            filename += '.jpg'
        elif type == 3:
            filename += '.aac'
        elif type == 4:
            filename += '.mov'
        print(filename)
        # 创建目录
        path = f"D:/pocket48image/{name}"
        if not os.path.exists(path):
            os.makedirs(path)

        html = requests.get(url, verify=False)
        fullpath = f'{path}/{filename}'
        with open(fullpath, 'wb') as f:
            f.write(html.content)
        f.close()
        api.wait_random_time(2)
        count += 1
        if count % 50 == 0:
            print(count, count / total)


def get_fanpai(cur_time, early_time):
    '''
    取翻牌的语音和视频
    10 语音 aac
    11 视频 mov
    '''
    result = db.data_inquiry_all("SELECT m.name,r.msg_type,r.ext_info,r.msg_time "
                                 "FROM pocket48.roommsg r left join "
                                 "member m on m.memberid=r.memberid where r.msg_type in (10,11) "
                                 "and m.fan_num<600000 and m.fan_num>0 "
                                 f"and r.msg_time>'{early_time}' and r.msg_time<'{cur_time}'")
    print(len(result))
    total = len(result)
    count = 0.0
    for data in result:
        ext = json.loads(data[2])
        url = json.loads(ext['answer'])['url']
        url = f'https://mp4.48.cn{url}'
        name = data[0]
        filename = data[3].strftime("%Y-%m-%d_%H-%M-%S")
        type = data[1]
        if type == 10:
            filename += '.aac'
        elif type == 11:
            filename += '.mp4'
        # 创建目录
        path = f"D:/pocket48image/fanpai/{name}"
        if not os.path.exists(path):
            os.makedirs(path)

        html = requests.get(url, verify=False)
        fullpath = f'{path}/{filename}'
        with open(fullpath, 'wb') as f:
            f.write(html.content)
        f.close()
        api.wait_random_time(2)
        count += 1
        if count % 50 == 0:
            print(count, count / total)


if __name__ == '__main__':
    config = configparser.ConfigParser()
    config.read(r'./config/config.ini', encoding='GB18030')
    start_time = config.get('member', 'start_time')
    end_time = config.get('member', 'end_time')
    get_roommsg_source(start_time, end_time)
    get_fanpai(start_time, end_time)